﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace viBook.ModelBinders
{
    public class ChapterUploadModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var dictionary = new List<KeyValuePair<string, HttpPostedFileBase>>();
            var folder = controllerContext.HttpContext.Request.Form.Get("path");
            var dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder);
            foreach (string file in controllerContext.HttpContext.Request.Files)
            {
                var postedFileBase = controllerContext.HttpContext.Request.Files[file];
                if (postedFileBase != null && postedFileBase.ContentLength > 0)
                {
                    var filename = DateTime.Now.ToString("dd-MM-yyyy") + "_" + DateTime.Now.Second.ToString("00") + Path.GetFileName(postedFileBase.FileName);
                    var savedFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder, filename);
                    dictionary.Add(new KeyValuePair<string, HttpPostedFileBase>(savedFilename, postedFileBase));
                }
            }
            return new { DirPath = dirPath, Dictionary = dictionary };
        }
    }
}